package com.uni.web.controller.system;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.uni.common.core.domain.entity.SysUserDO;
import com.uni.common.core.domain.model.LoginUser;
import com.uni.framework.web.service.TokenService;
import com.uni.system.mapper.SysUserMapper;
import com.uni.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.*;

import com.uni.common.security.RsaUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.uni.common.constant.Constants;
import com.uni.common.core.domain.AjaxResult;
import com.uni.common.core.domain.entity.SysMenu;
import com.uni.common.core.domain.entity.SysUser;
import com.uni.common.core.domain.model.LoginBody;
import com.uni.common.utils.SecurityUtils;
import com.uni.framework.web.service.SysLoginService;
import com.uni.framework.web.service.SysPermissionService;
import com.uni.system.service.ISysMenuService;

import javax.annotation.Resource;

/**
 * 登录验证
 *
 * @author uni
 */
@Api(tags = {"系统：登录接口"})
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private RsaUtils rsaUtils;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(value = "账户密码登录", notes = "通过用户名和密码登录系统")
    @PostMapping("/login")
    public AjaxResult login(
            @ApiParam(value = "登录信息", required = true)
            @RequestBody LoginBody loginBody) {
        System.out.println("loginBody = " + loginBody);
        AjaxResult ajax = AjaxResult.success();
        // 对前端传入的密码进行解密
        try {
            loginBody.setPassword(rsaUtils.decryptByPrivateKey(loginBody.getPassword()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 手机号码登录
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(value = "手机号码登录", notes = "通过手机号和验证码登录系统")
    @PostMapping("/smsLogin")
    public AjaxResult smsLogin(@ApiParam(value = "登录信息", required = true) @RequestBody LoginBody loginBody) {
        System.out.println("loginBody = " + loginBody);
        AjaxResult ajax = AjaxResult.success();
        String token = loginService.smsLogin(loginBody.getTelephone(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation(value = "获取当前登录用户信息", notes = "返回当前登录用户的详细信息")
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation(value = "获取当前登录用户菜单树", notes = "返回当前登录用户的菜单树信息")
    @GetMapping("/getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    @Autowired
    private ISysUserService userService;


    @Autowired
    private SysUserMapper userMapper;

    @Resource
    WxMaService wxMaService;

    @Autowired
    private TokenService tokenService;

    /**
     * 采用微信javaSDK实现微信小程序登录
     * @param code
     * @return
     */
    public Map<String, Object> wxLoginx(String code) {
        try {
            //根据code调用微信SDK获取用户会话信息 得到微信用户唯一标识
//            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            WxMaJscode2SessionResult sessionInfo = new WxMaJscode2SessionResult();
            sessionInfo.setOpenid(UUID.randomUUID().toString());//模拟一个假的微信openid


            if (sessionInfo != null) {
                String openid = sessionInfo.getOpenid();
                //根据openid查询用户记录
                LambdaQueryWrapper<SysUserDO> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SysUserDO::getWxOpenid,openid);
                SysUserDO userInfo = userService.getOne(queryWrapper);

                //根据openid未得到用户记录 新增用户记录且采用MQ异步初始化账户（余额）信息
                if(userInfo==null){
                    userInfo = new SysUserDO();
                    userInfo.setWxOpenid(openid);
                    userInfo.setNickName("用户" + IdUtil.getSnowflake().nextId());
                    userInfo.setUserName(userInfo.getNickName());
                    userInfo.setAvatar("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
                    userMapper.insert(userInfo);
                }
                //根据openid获取用户记录

                SysUser myuser = new SysUser();
                myuser.setWxOpenid(userInfo.getWxOpenid());
                myuser.setNickName(userInfo.getNickName());
                myuser.setUserName(userInfo.getUserName());
                myuser.setAvatar("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");

                //为登录微信用户生成令牌并存到redis
                LoginUser loginUser = new LoginUser();
                loginUser.setUser(myuser);
                loginUser.setUserId(myuser.getUserId());

                String token =  tokenService.createToken(loginUser);
                //响应令牌
                Map<String,Object> mapResult = new HashMap<>();
                mapResult.put("token", token);
                return mapResult;

            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取部门树列表
     */
    @PostMapping("/wxLogin")
    public AjaxResult wxLogin(String code)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.putAll(wxLoginx(code));
        return AjaxResult.success(ajax);
    }
}
